/*
 * @Author: xiaosihan
 * @Date: 2025-01-20 16:42:44
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2025-01-22 14:36:59
 */
import { Mesh, Object3D, WebGLRenderer } from "three";
import { MeshoptDecoder } from "three/examples/jsm/libs/meshopt_decoder.module.js";
import {
  GLTFLoader,
  DRACOLoader,
  KTX2Loader,
} from "three/examples/jsm/Addons.js";

import toStanderMaterial from "./toStanderMaterial";

const gltfLoader = new GLTFLoader();
const dracoLoader = new DRACOLoader();
gltfLoader.setDRACOLoader(dracoLoader.setDecoderPath("/three_gltf/"));
const ktx2Loader = new KTX2Loader().setTranscoderPath("/basis/");
if (document) {
  ktx2Loader.detectSupport(new WebGLRenderer({ precision: "highp" }));
}
gltfLoader.setKTX2Loader(ktx2Loader);
gltfLoader.setMeshoptDecoder(MeshoptDecoder);

// 进入ar应用 传入模型的地址
export default async function activeXR(url: string) {
  if (import.meta.server) {
    return;
  }

  const { default: browserTool } = await import("browser-tool");
  // 获取浏览器详细信息 - 全部字段
  let info = await browserTool.getInfo();

  const { browser, platform, system } = info;
  console.log({ browser, platform, system });
  //    alert(JSON.stringify({ browser, platform, system }));
  //如果是苹果浏览器就用a标签唤起自带的ar
  //   location.href = `/arcode?url=${url}`;
  //   return;
  if (
    system === "iOS" &&
    browser === "Safari" &&
    ["iPhone", "iPad"].includes(platform)
  ) {
    //如果是usdz格式就直接唤起如果不是usdz就要转一下格式
    const link = document.createElement("a");
    link.appendChild(document.createElement("img"));
    link.setAttribute("rel", "ar");

    //判断 url 是不是 .usdz 结尾
    if (url.endsWith(".usdz")) {
      link.setAttribute("href", url);

      //如果是glb格式的就要转换一下格式
    } else if (url.endsWith(".glb")) {
      const gltfModel = await gltfLoader.loadAsync(url);
      const { USDZExporter } = await import("three/examples/jsm/Addons.js");
      const exporter = new USDZExporter();
      if (gltfModel.scene) {
        gltfModel.scene.traverse((o: Object3D) => {
          const mesh = o as Mesh;
          if (mesh.isMesh) {
            // 把非标准材质都转到标准材质
            mesh.material = toStanderMaterial(mesh.material);
          }
        });
      }
      const arraybuffer = await exporter.parseAsync(gltfModel.scene);
      const blob = new Blob([arraybuffer], {
        type: "model/vnd.usdz+zip",
      });
      const blobUrl = URL.createObjectURL(blob);
      link.setAttribute("href", blobUrl);
      link.setAttribute("download", "model.usdz");
    }

    link.click();
  } else if (system === "Android") {
    // browser "OPPO" "DingTalk" "Chrome" "Vivo"
    location.href = `/arcode?url=${url}`;
  }
}
